package com.chookss.home.knowledge.adaper;

import android.app.Activity;
import android.content.Intent;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.document.DownloadService;
import com.chookss.home.entity.DocunmentEntity;
import com.chookss.home.entity.GalleryListEntity;
import com.chookss.home.entity.UploadEntity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.bigImage.ImagePreview;
import com.chookss.tools.bigImage.bean.ImageInfo;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.VideoOnePlayActivity;
import com.chookss.video.entity.VideoEntity;
import com.chookss.video.recommend.VedioDetailActivity;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.annotations.Nullable;

public class UploadAdapter extends BaseQuickAdapter<UploadEntity, BaseViewHolderEx> {
    private Activity context;
    private String tag;//记录来源
    private int type;//0首页 1上传列表
    private boolean isTask = false;

    public UploadAdapter(int layoutResId, Activity context, @Nullable List<UploadEntity> data, int type, String tag) {
        super(layoutResId, data);
        this.context = context;
        this.tag = tag;
        this.type = type;
    }

    @Override
    protected void convert(BaseViewHolderEx helper, UploadEntity entity) {
        ImageView ivIconType = helper.getView(R.id.ivIconType);
        LinearLayout llContent = helper.getView(R.id.llContent);
        LinearLayout llTitle = helper.getView(R.id.llTitle);
        TextView tvItemTitle = helper.getView(R.id.tvItemTitle);
        TextView tvItemDate = helper.getView(R.id.tvItemDate);
        TextView tvItemSize = helper.getView(R.id.tvItemSize);
        TextView tvItemInit = helper.getView(R.id.tvItemInit);
        ProgressBar progressBar = helper.getView(R.id.progressBar);
        LinearLayout.LayoutParams ivParams = (LinearLayout.LayoutParams) ivIconType.getLayoutParams();
        LinearLayout.LayoutParams llContentParams = (LinearLayout.LayoutParams) llContent.getLayoutParams();
        LinearLayout.LayoutParams llTitleParams = (LinearLayout.LayoutParams) llTitle.getLayoutParams();
        tvItemTitle.setMaxLines(1);
        tvItemTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        tvItemDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        tvItemInit.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        tvItemSize.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        llContentParams.setMargins(Utils.dip2px(context, 10), 0, Utils.dip2px(context, 15), 0);
        llTitleParams.setMargins(0, 0, 0, Utils.dip2px(context, 5));
        if (type == 1) {
            ivParams.setMargins(Utils.dip2px(context, 15), 0, 0, 0);
        } else {
            ivParams.setMargins(Utils.dip2px(context, 12), 0, 0, 0);
        }
        ivIconType.setLayoutParams(ivParams);
        llContent.setLayoutParams(llContentParams);
        llTitle.setLayoutParams(llTitleParams);
//        （1资料，2长视频，3短视频，4新闻，5图文6图片）
        int resourceType = Utils.changeNumber(entity.getResourceType());
        if (1 == resourceType) {
            if (entity.getDataBase().getProgress() == 0 || entity.getDataBase().getProgress() == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(entity.getDataBase().getProgress());
            }
            String fileType = entity.getDataBase().getFileType();//文件类型1--word 2 --excel 3--PPT  4pdf
            if ("1".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_w_80).into(ivIconType);
            } else if ("2".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_x_80).into(ivIconType);
            } else if ("3".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_p_80).into(ivIconType);
            } else if ("4".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_pdf_80).into(ivIconType);
            } else {
                Glide.with(context).load(R.drawable.icon_mr_80).into(ivIconType);
            }
            tvItemTitle.setText(entity.getDataBase().getDataTitle());
            tvItemSize.setText(Utils.changeKM(entity.getDataBase().getDataSize()));
        } else if (2 == resourceType || 3 == resourceType) {
            GlideUtils.loadCustomRound(context, entity.getVideo().getVideoCoverPath(), ivIconType, 4);
            tvItemTitle.setText(entity.getVideo().getVideoTitle());
            tvItemSize.setText(Utils.changeKM(entity.getVideo().getVideoSize()));
        } else if (6 == resourceType) {
            GlideUtils.loadCustomRound(context, entity.getImage().getImagePath(), ivIconType, 4);
            tvItemTitle.setText(entity.getImage().getImageTitle());
            tvItemSize.setText(Utils.changeKM(entity.getImage().getImageSize()));
        }
        if (type == 1) {
            //列表
            tvItemDate.setVisibility(View.VISIBLE);
            if (1 == resourceType) {
                tvItemDate.setText(Utils.getAccurateDate(entity.getDataBase().getUploadTime()));
                tvItemInit.setText(entity.getDataBase().getDataPath());
            } else if (2 == resourceType || 3 == resourceType) {
                tvItemDate.setText(Utils.getAccurateDate(entity.getVideo().getCreateTime()));
                tvItemInit.setText(entity.getVideo().getBelgCatalog());
            }else if (6 == resourceType) {
                tvItemDate.setText(Utils.getAccurateDate(entity.getImage().getCreateTime()));
                tvItemInit.setText(entity.getImage().getCatalogNames());
            }
        } else {
            //首页
            tvItemDate.setVisibility(View.GONE);
            if (1 == resourceType) {
                tvItemInit.setText(Utils.getAccurateDate(entity.getDataBase().getUploadTime()));
            } else if (2 == resourceType || 3 == resourceType) {
                tvItemInit.setText(Utils.getAccurateDate(entity.getVideo().getCreateTime()));
            } else if (6 == resourceType ) {
                tvItemInit.setText(Utils.getAccurateDate(entity.getImage().getCreateTime()));
            }
        }
        helper.getItemView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Urls.antiShake.check()) {
                    return;
                }
                if (resourceType == 1) {
                    requestSTORAGE(entity.getDataBase().getDataCode(), tvItemTitle.getText().toString(), helper.getItemPosition(),entity.getDataBase().isError());
                } else if (resourceType == 2 || resourceType == 3) {
                    getVideo(entity.getVideo().getVideoId(), resourceType);
                }else if (resourceType == 6) {
                    getPicDetail(entity.getImage().getImageCode());
                }
            }
        });
    }
    private void getPicDetail(String imageCode) {
        Map<String, String> allmap = new HashMap<>();
        allmap.put("imageCode", imageCode);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<GalleryListEntity.ImagePathListBean>>() {
        }.getType(), null, Urls.getImageDetail, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<GalleryListEntity.ImagePathListBean>() {
            @Override
            public void onSuccess(GalleryListEntity.ImagePathListBean data) {
                if (data != null) {
                    List<ImageInfo> imageInfoList = new ArrayList<>();
                    imageInfoList.add(dealData(data));
                    ImagePreview.getInstance()
                            .setContext(context)
                            // 设置从第几张开始看（索引从0开始）
                            .setIndex(0)
                            .setShowCloseButton(true)
                            .setToNewView(true)
                            .setLoadStrategy(ImagePreview.LoadStrategy.NetworkAuto)
                            .setImageInfoList(imageInfoList)
                            .start();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private ImageInfo dealData(GalleryListEntity.ImagePathListBean imagePathListBean) {
        ImageInfo imageInfo = new ImageInfo();
        String originUrl = imagePathListBean.getImagePath().split("\\?")[0];
//                    imageInfo.setThumbnailUrl(originUrl+"?x-oss-process=image/resize,m_lfit,w_720");
        imageInfo.setThumbnailUrl(originUrl);
        imageInfo.setOriginUrl(originUrl);
        imageInfo.setImageCode(imagePathListBean.getImageCode());
        if (Utils.isNull(imagePathListBean.getProvideEmployeeName())) {
            imageInfo.setName(imagePathListBean.getCreateEmployeeName());
        } else {
            imageInfo.setName(imagePathListBean.getProvideEmployeeName());
        }
        String date = imagePathListBean.getCreateTime();
        if (!Utils.isNull(date)) {
            if (date.length() >= 17) {
                imageInfo.setDay(Utils.getNormalYMDTime(date.substring(0, 10)));
                imageInfo.setMinutes(date.substring(11, 16));
                imageInfo.setDate(date.substring(0, 10));
            } else {
                imageInfo.setDay("");
                imageInfo.setMinutes("");
                imageInfo.setDate("");
            }
        } else {
            imageInfo.setDay("");
            imageInfo.setMinutes("");
            imageInfo.setDate("");
        }
        imageInfo.setLocation(imagePathListBean.getImageUploadLocationProvince() + " " + imagePathListBean.getImageUploadLocationCity());
        return imageInfo;
    }
    private void requestSTORAGE(String dataCode, String retitle, int rePosition,boolean isError) {
        XXPermissions.with(context)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            getDocunmentDetail(dataCode, retitle, rePosition,isError);
                        } else {
                            MyToast.show("存储未被授权，请先去权限设置里面授权");
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(context, denied, quick);
                    }
                });
    }

    private void getDocunmentDetail(String dataCode, String docTitle, int docPosition,boolean isError) {
        Map<String, String> map = new HashMap<>();
        map.put("dataCode", dataCode);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<DocunmentEntity>>() {
        }.getType(), null, Urls.getDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<DocunmentEntity>() {
            @Override
            public void onSuccess(DocunmentEntity newData) {
                if (newData != null) {
                    openFile(newData, docTitle, docPosition,isError);
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void openFile(DocunmentEntity entity, String title, int position,boolean isError) {
        if (!Utils.isNull(entity.getDataUrl())) {
            String url, name, fileUrl, urls;
            url = entity.getDataUrl();
            urls = url.split("\\?")[0];
            fileUrl = urls.substring(urls.lastIndexOf("/") + 1, urls.length());
            if (MyApp.downloadFiles.contains(title)||!MyApp.mIsInitTBSSuccess||isError) {
                if (!MyApp.docunmentOpen) {
                    Intent intent = new Intent(context, DocumentPreviewActivity.class);
                    intent.putExtra("fileUrl", fileUrl);
                    intent.putExtra("fileName", title);
                    intent.putExtra("dataCode", entity.getDataCode());
                    if (isTask) {
                        intent.putExtra("type", 1);
                    }
                    context.startActivity(intent);
                }
            } else {
//                    downTask(url, title, entity, position);
                entity.setProgress(1);
                notifyItemChanged(position);
                Intent intent = new Intent(context, DownloadService.class);
                intent.putExtra("fileUrl", fileUrl);
                intent.putExtra("fileName", title);
                intent.putExtra("url", url);
                intent.putExtra("dataCode", entity.getDataCode());
                intent.putExtra("position", position);
                intent.putExtra("tag", tag);
                context.startService(intent);
            }

        }
    }

    private void getVideo(String id, int type) {
        Map<String, String> map = new HashMap<>();
        map.put("videoId", id);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<VideoEntity>>() {
        }.getType(), null, Urls.selectAPPVideoById, SignUtils2.makeSignStr(map), false, new ObserverCallback<VideoEntity>() {
            @Override
            public void onSuccess(VideoEntity data) {
                if (Utils.isNull(data.videoId)) {
                    MyToast.show("视频id为空");
                    return;
                }
                if (type == 2) {
                    Intent intent = new Intent(context, VedioDetailActivity.class);
                    intent.putExtra("video", data);
                    context.startActivity(intent);
                } else {
                    Intent intent = new Intent(context, VideoOnePlayActivity.class);
                    intent.putExtra("watermark", "2");
                    intent.putExtra("video", data);
                    context.startActivity(intent);
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

}
